/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.saashousekeeper.config.dynamicdatasource;

import com.huawei.saashousekeeper.config.balancestrategy.LoadBalanceStrategy;
import com.huawei.saashousekeeper.config.TenantContext;
import com.huawei.saashousekeeper.constants.CommonConstants;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.util.List;

/**
 * 数据源组
 *
 * @author lWX1156935
 * @since 2022/4/22
 */
@Data
@AllArgsConstructor
@Log4j2
public class DataSourceGroup {

    private LoadBalanceStrategy loadBalanceStrategy;
    private List<DataSource> masterGroup;
    private List<DataSource> slaveGroup;

    /**
     * 获取组
     *
     * @return 数据源组
     */
    public DataSource getDataSource() {
        String dbStrategy = TenantContext.getDbStrategyType();
        boolean selectMaster = CommonConstants.DB_MASTER.equalsIgnoreCase(dbStrategy) ||  CollectionUtils.isEmpty(slaveGroup);
        log.warn("{} select db {}", TenantContext.getDomain(), selectMaster ? CommonConstants.DB_MASTER : CommonConstants.DB_SLAVE);
        return selectMaster ? loadBalanceStrategy.get(masterGroup) : loadBalanceStrategy.get(slaveGroup);
    }
}
